const fs = require('fs')
const uuid = require('uuid');
import { ObjectId, MongoClient } from 'mongodb'
import YAML from 'yamljs'

import BaseResult from '../lib/BaseResult'

const { mongo } = YAML.parse(fs.readFileSync('./server/config.yaml').toString());
const url = mongo.host;


class SysController {
    static async editAppInfo(ctx) {
        let data = ctx.request.body;

        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                if (data.appKey) {
                    let whereStr = { appKey: data.appKey };
                    dbo.collection("app").updateOne(whereStr, data, function(err, res) {
                        if (err) throw err;
                        // console.log("文档更新成功");
                        ctx.body = new BaseResult(0, 0, null);
                        db.close();
                    });
                } else {
                    //data.appKey = uuid.v1();
                    dbo.collection("app").insertOne(data, function(err, res) {
                        if (err) throw err;
                        // console.log("文档插入成功");
                        // ctx.body = "文档插入成功";
                        ctx.body = new BaseResult(0, 0, null);
                        resolve();
                        db.close();
                    });
                }

            });
        })
    }
    static async apps(ctx) {
        //  ctx.body = new BaseResult(0, null, data)
        let data = ctx.request.body;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("app").find({}).toArray(function(err, res) {
                    if (err) throw err;
                    //console.log("文档插入成功");
                    //ctx.body = res;
                    ctx.body = new BaseResult(0, 0, res);
                    resolve();
                    db.close();
                });
            });
        })
    }
    static async getApp(ctx) {}
    static async configure(ctx) {}
    static async debugjs(ctx) {}
}
export default  SysController;